#include "server_udp_wrapper.h"
#include "udpagent.h"
#include "udprequest.h"
#include "basic_tool.h"
#include "config.h"

ServerUdpWrapper::ServerUdpWrapper()
{
  m_pUdpAgent = new UdpAgent;
  m_pServer = new Server;
  m_pServer->Setup();
}

ServerUdpWrapper::~ServerUdpWrapper()
{
  delete m_pUdpAgent;
  delete m_pServer;
}

int ServerUdpWrapper::Start()
{
  unsigned short portnum = Config::m_authenserver_port;
  cout<<"listen on address "<<Config::m_authenserver_ip<<" port "<<portnum<<endl;
  m_pUdpAgent->Bind(Config::m_authenserver_ip, portnum);
  struct sockaddr_in sockaddClient;
  UdpSigRequest * pReq = new UdpSigRequest;
  UdpSigResponse * pRes = new UdpSigResponse;
  int n;
  while((n = m_pUdpAgent->RecvFrom((char *) pReq, sizeof(UdpSigRequest), sockaddClient)))
	{
	  cout<<"Request from "<< inet_ntoa (sockaddClient.sin_addr)<<endl;
	  assert(pReq->Type() == 10);
	  // parse request
	  pRes->RequestId() = pReq->RequestId();
      pRes->SubRequestId() = pReq->SubRequestId();
	  m_pServer->OnRequest(pRes->GetSig(), (size_t&) pRes->SigLength(), SIG_LEN,
						   pReq->GetSig(), (size_t) pReq->SigLength());
	  m_pUdpAgent->SendTo((char *)pRes, sizeof(UdpSigResponse), sockaddClient);
      cout<<"send response for requestid="<<pRes->RequestId()<<" subrequestid="<<pRes->SubRequestId()<<endl;
	}
  return 0;  
}
